// 日志级别
export const LogLevel = {
  DEBUG: 'debug',
  INFO: 'info',
  WARNING: 'warning',
  ERROR: 'error'
}

// 日志记录器（单例模式）
export class Logger {
  static instance = null
  
  constructor() {
    this.logs = []
    this.listeners = []
    this.maxLogs = 100 // 最大日志条数
  }
  
  static getInstance() {
    if (!this.instance) {
      this.instance = new Logger()
    }
    return this.instance
  }
  
  // 添加日志
  log(level, message, data = null) {
    const logEntry = {
      level,
      message,
      data,
      timestamp: new Date()
    }
    
    this.logs.unshift(logEntry) // 新日志添加到前面
    
    // 控制日志数量
    if (this.logs.length > this.maxLogs) {
      this.logs = this.logs.slice(0, this.maxLogs)
    }
    
    // 通知监听器
    this.notifyListeners(logEntry)
    
    // 同时输出到控制台
    switch (level) {
      case LogLevel.DEBUG:
        console.debug(message, data)
        break
      case LogLevel.INFO:
        console.info(message, data)
        break
      case LogLevel.WARNING:
        console.warn(message, data)
        break
      case LogLevel.ERROR:
        console.error(message, data)
        break
      default:
        console.log(message, data)
    }
    
    return logEntry
  }
  
  // 快捷方法
  debug(message, data = null) {
    return this.log(LogLevel.DEBUG, message, data)
  }
  
  info(message, data = null) {
    return this.log(LogLevel.INFO, message, data)
  }
  
  warning(message, data = null) {
    return this.log(LogLevel.WARNING, message, data)
  }
  
  error(message, data = null) {
    return this.log(LogLevel.ERROR, message, data)
  }
  
  // 获取所有日志
  getLogs() {
    return [...this.logs]
  }
  
  // 清空日志
  clearLogs() {
    this.logs = []
    this.notifyListeners({ type: 'clear' })
  }
  
  // 添加监听器
  addListener(listener) {
    if (typeof listener === 'function' && !this.listeners.includes(listener)) {
      this.listeners.push(listener)
      return true
    }
    return false
  }
  
  // 移除监听器
  removeListener(listener) {
    const index = this.listeners.indexOf(listener)
    if (index !== -1) {
      this.listeners.splice(index, 1)
      return true
    }
    return false
  }
  
  // 通知所有监听器
  notifyListeners(logEntry) {
    this.listeners.forEach(listener => {
      try {
        listener(logEntry)
      } catch (e) {
        console.error('日志监听器执行错误:', e)
      }
    })
  }
} 